package com.easy.dn.ui.usercenter.activity;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easy.common.base.BaseActivity;
import com.easy.common.commonutils.SPUtils;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonwidget.RippleView;
import com.easy.common.commonwidget.dialog.CustomDialog;
import com.easy.dn.api.ApiConstants;
import com.easy.dn.app.AppConstant;
import com.easy.dn.app.GlobalApplication;
import com.easy.dn.bean.CodeBean;
import com.easy.dn.bean.CodeVerificationBean;
import com.easy.dn.bean.UserInfoBean;
import com.easy.dn.ui.usercenter.contract.RegisterContract;
import com.easy.dn.ui.usercenter.model.RegisterModel;
import com.easy.dn.ui.usercenter.presenter.RegisterPresenter;
import com.easy.dn.utils.DnUtils;
import com.easy.dn.utils.MapHelper;
import com.easy.dn.utils.encryption.EncryUtils;
import com.easy.dn.utils.encryption.RSACoder;
import com.easy.dn.widget.InputMethodRelativeLayout;
import com.easy.dn.widget.TimeCount;
import com.qmuiteam.qmui.util.QMUIViewHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import dn.easy.com.easyto.R;
import rx.Observable;
import rx.Observer;

import static dn.easy.com.easyto.R.id.getCodeBtn;
import static dn.easy.com.easyto.R.id.registerBtn;
import static dn.easy.com.easyto.R.id.userName;

/**
 * ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
 * ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
 * ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
 * ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
 * ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
 * ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
 * ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
 * ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
 * ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
 * ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
 * ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
 * 单身狗就这样默默地看着你，一句话也不说。
 * -->注册
 *
 * @author DN
 * @data 2017/9/6
 **/
public class RegisterActivity extends BaseActivity<RegisterPresenter, RegisterModel> implements RegisterContract.View, InputMethodRelativeLayout.OnSizeChangedListenner, RippleView.OnRippleCompleteListener {


    @Bind(R.id.iv_img_backgroud)
    ImageView mIvImgBackgroud;
    @Bind(R.id.tv_registerBack)
    TextView mTvRegisterBack;
    @Bind(R.id.de_frm_backgroud)
    FrameLayout mDeFrmBackgroud;
    @Bind(R.id.backBtnRegister)
    Button mBackBtnRegister;
    @Bind(R.id.loginLogoLayout)
    ImageView mLoginLogoLayout;
    @Bind(R.id.tv_title_text)
    LinearLayout mTitleText;
    @Bind(R.id.linear)
    LinearLayout mLinear;
    @Bind(R.id.country)
    TextView mCountry;
    @Bind(R.id.CountryName)
    TextView mCountryName;
    @Bind(R.id.spinnerRegisterCountry)
    Spinner mSpinnerRegisterCountry;
    @Bind(R.id.countryCode)
    TextView mCountryCode;
    @Bind(userName)
    EditText mUserName;
    @Bind(getCodeBtn)
    RippleView mGetCodeBtn;
    @Bind(R.id.usercenterRegisterPhone)
    TextView mUsercenterRegisterPhone;
    @Bind(R.id.code)
    EditText mCode;
    @Bind(R.id.usercenterPassword)
    TextView mUsercenterPassword;
    @Bind(R.id.pass)
    EditText mPass;
    @Bind(R.id.seePassword)
    TextView mSeePassword;
    @Bind(R.id.VerifyPassword)
    TextView mVerifyPassword;
    @Bind(R.id.samePass)
    EditText mSamePass;
    @Bind(R.id.usercenterNickname)
    TextView mUsercenterNickname;
    @Bind(R.id.nickname)
    EditText mNickname;
    @Bind(R.id.codeBtn)
    Button mCodeBtn;
    @Bind(registerBtn)
    RippleView mRegisterBtn;
    @Bind(R.id.agreementInfo)
    TextView mAgreementInfo;
    @Bind(R.id.scroll)
    ScrollView mScroll;
    @Bind(R.id.loginpage)
    InputMethodRelativeLayout mLoginpage;

    private CustomDialog mAlertDialog;
    private String mVKey = "";
    private int mVKeyDown;
    private String mCodeStr;
    private TimeCount time;

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        mLoginpage.setOnSizeChangedListenner(this);
        mGetCodeBtn.setOnRippleCompleteListener(this);
        mRegisterBtn.setOnRippleCompleteListener(this);

        Observable.interval(20, TimeUnit.MILLISECONDS)
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Long number) {
                        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.translate_anim);
                        mIvImgBackgroud.startAnimation(animation);
                    }
                });
        time = new TimeCount(60000 * 1, 1000, mCodeBtn);// 构造CountDownTimer对象
        loadCookieData();


        //记录上次登录的手机号 对用户有好一点
        if (!StringUtils.isEmpty(SPUtils.getSharedStringData(mContext, AppConstant.LOGINPHONE)))
            mUserName.setText(SPUtils.getSharedStringData(mContext, AppConstant.LOGINPHONE));
    }

    /**
     * 获取是否需要图形验证码 +　Ｃｏｏｋｉｅ　本地保存
     */
    private void loadCookieData() {
        Map<String, String> map = MapHelper.getAccessMap();
        map.put("types", "img_code");
        mPresenter.getCodeInfoData(map);
    }


    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.getCodeBtn:
                String phoneNumber = mUserName.getText().toString().trim();
//                String mPassWord = mPass.getText().toString().trim();
                if (!StringUtils.isEmpty(phoneNumber)) {
                    //获取验证码
                    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                    View dialogView = inflater.inflate(R.layout.dialog_code, null);
                    final ImageView CodeImg = (ImageView) dialogView.findViewById(R.id.codeImg);
//                final EditText messageEdit = (EditText) dialogView.findViewById(R.id.message);
                    final String imgPath = ApiConstants.URL + "p/code.jpg?client_type=1&" + SPUtils.getSharedStringData(GlobalApplication.getInstance(), "Cookie").replace("JSESSIONID", "jsessionid");
                    Log.i("okhttp:Cookie-->0:", imgPath);
                    mAlertDialog = DnUtils.showCustomDialog(mContext, "", R.layout.dialog_code)
                            .setOnclickListener(R.id.cancelButton, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    mAlertDialog.dismiss();
                                }
                            }).setOnclickListener(R.id.okButton, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    EditText messageEdit = (EditText) mAlertDialog.getView(R.id.message);
                                    mCodeStr = messageEdit.getText().toString().trim();
                                    Log.i("DnLOG", messageEdit.getText().toString());
                                    if (!StringUtils.isEmpty(mCodeStr)) {
                                        mVKeyDown = 1;
                                        startProgressDialog();
                                        loadCodeData(mCodeStr);
                                        mAlertDialog.dismiss();
                                    } else
                                        showShortToast(mContext.getResources().getString(R.string.code));
                                }
                            }).setOnclickListener(R.id.tv_chanage_img, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Glide.with(RegisterActivity.this)
                                            .load(imgPath)
                                            .asBitmap()
                                            .skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                                            .error(R.drawable.ic_empty_picture)
                                            .into((ImageView) mAlertDialog.getView(R.id.codeImg));

                                }
                            }).setImage(R.id.codeImg, imgPath)
                            .show();
                } else
                    DnUtils.showToast(mRegisterBtn, mContext.getResources().getString(R.string.write_phone));

                break;
            case registerBtn:
                //注册
                String mPhoneNumber = mUserName.getText().toString().trim();
                String mPassWord = mPass.getText().toString().trim();
                String mNickName = mNickname.getText().toString().trim();
                String mCodeStr = mCode.getText().toString().trim();
                if (!StringUtils.isEmpty(mPhoneNumber) && StringUtils.isNumeric(mPhoneNumber)) {
                    if (!StringUtils.isEmpty(mCodeStr)){
                        if (!StringUtils.isEmpty(mPassWord) && mPassWord.length() > 5 && !StringUtils.isContainChinese(mPassWord)) {
                            if (!StringUtils.isEmpty(mNickName) && mNickName.length() < 21) {
                                Map<String, String> map = new HashMap<String, String>();
                                try {
                                    map.put("phone", mPhoneNumber);
                                    map.put("password", RSACoder.encrypt(mPassWord));
                                    map.put("nickname", mNickName);
                                    map.put("vCode", mCodeStr);
                                    map.put("areaCode", "86"); //这个还没做 。。。
                                    mPresenter.getRegistgerData(map);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } else
                                DnUtils.showToast(mRegisterBtn, mContext.getResources().getString(R.string.write_nickname));
                         }else
                            DnUtils.showToast(mRegisterBtn, mContext.getResources().getString(R.string.pass_not_null));
                    } else
                        DnUtils.showToast(mRegisterBtn, mContext.getResources().getString(R.string.write_code));
                } else
                    DnUtils.showToast(mRegisterBtn, mContext.getResources().getString(R.string.write_phone));
                break;
            default:
                break;
        }
    }

    private void loadCodeData(String vCode) {

        JSONObject jsonObject = new JSONObject();
        Map<String, String> map = new HashMap<String, String>();
        String data = "";
        try {
            jsonObject.put("phone", mUserName.getText().toString());
            jsonObject.put("area_code", "86");
            jsonObject.put("type", "1");
            jsonObject.put("vkey", mVKey);
            jsonObject.put("vcode", vCode);
            jsonObject.put("client_type", "1");
            map = EncryUtils.clientEncrypt(jsonObject.toString());
            map.put("mode", "1");
            map.put("dev_type", "app");
            mPresenter.getCodeVerificationData(map);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void returnUserInfoData(UserInfoBean loginInfoBean) {

    }

    @Override
    public void returnCodeInfoData(CodeBean codeBean) {
        Log.i("okhttp:Cookie-->:", SPUtils.getSharedStringData(GlobalApplication.getInstance(), "Cookie"));
    }

    @Override
    public void returnRegistgerData(UserInfoBean registerBean) {

    }

    @Override
    public void returnCodeVerificationData(CodeVerificationBean codeVerificationBean) {
        mVKey = codeVerificationBean.getVkey();
        if (mVKeyDown == 1) {
            loadCodeData(mCodeStr);
        } else if (mVKeyDown == 2) {
            time.start();// 开始计时
            showShortToast(R.string.request_sended);
            stopProgressDialog();
        }
        mVKeyDown++;
    }

    @Override
    public void showLoading(String title) {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorTip(String msg) {
        DnUtils.showToast(mRegisterBtn, msg);
        stopProgressDialog();
    }

    @Override
    public void onSizeChange(boolean paramBoolean, int w, int h) {
        if (paramBoolean) {// 键盘弹出时
            QMUIViewHelper.fadeOut(mTitleText, 500, null, true);
        } else { // 键盘隐藏时
            QMUIViewHelper.fadeIn(mTitleText, 500, null, true);

        }
    }
}
